package com.zcsy.manage.web.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.Globals;
import com.zcsy.commons.util.MD5Util;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.model.system.RoleUser;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.company.IDistributionCompanyService;
import com.zcsy.manage.service.company.IOperationCompanyService;
import com.zcsy.manage.service.company.IPropertyCompanyService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.common.LogUtils;

import net.sf.json.JSONArray;

/**
 * @ClassName: UserController
 * @Description: 用户控制层管理类
 * @author xujl 850789178@qq.com
 * @date 2016年1月8日
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    
    private static final int USER_STATE = 1;          // 初始化新增用户状态为1
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IRoleService roleService;
    
    @Autowired
    private IDictService dictService;
    
	@Autowired
	private IOperationCompanyService operationCompanyService;
	
	@Autowired
	private IPropertyCompanyService propertyCompanyService;
	
	@Autowired
	private IShopInfoService shopInfoService;
	
	@Autowired
	private IDistributionCompanyService distributionCompanyService;
	
    /**
     * 分页获取数据列表
     * 
     * @param pageNo
     *            起始页
     * @param uname
     *            用户名
     * @param lname
     *            登录名
     * @param req
     *            用户请求
     * @return
     */
    @RequestMapping(value = "userList", method = RequestMethod.GET)
    public String getUserListBySearchKey(Model model, Integer userType, Integer pageNo, Integer pSize, String uname, String lname, String phoneNo, HttpServletRequest req) {

        if (pageNo == null) {
            pageNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pageNo, pageSize);
        User record = new User();

        // 用户名为不空字符串时，设置用户名
        if (!"".equals(uname)) {
            record.setUsername(uname);
        }

        // 登录名为不空字符串时，设置登录名
        if (!"".equals(lname)) {
            record.setLoginname(lname);;
        }

        if(!"".equals(userType)){
            record.setUserType(userType);
        }
        
        if(!"".equals(phoneNo)){
            record.setPhone(phoneNo);
        }
        List<User> userList = userService.queryUser(record);
        PageInfo<User> info = new PageInfo<User>(userList);

        model.addAttribute("userInfo", info);
        model.addAttribute("uname", uname);
        model.addAttribute("lname", lname);
        model.addAttribute("userType", userType);
        model.addAttribute("currentPage", pageNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("phoneNo", phoneNo);
		
		model.addAttribute("defaultPwd", Globals.getConfig("account_password"));

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "system/user/userList";
    }
    

    /**
     * Description: 新增或修改用户对象
     * 
     * @param userVo
     *            用户对象
     * @param req
     *            用户请求
     * @return 请求结果
     * @author xujl 850789178@qq.com
     * @see
     */
    @RequestMapping(value = "editUser", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateUser(String nickname,String uname,
    		String phone,String email,Integer sex,String orgId,String id,
    		@RequestParam(value="roles[]") String[] roles,Integer userType,
    		String companyId,@RequestParam(value="shopIds[]") String[] shopIds,HttpServletRequest request) {
        RequestJson result = new RequestJson();
        
        User userVo = new User();
        userVo.setUsername(uname);
        userVo.setNickname(nickname);
        userVo.setSex(sex);
        userVo.setPhone(phone);
        userVo.setEmail(email);
        userVo.setOrgId(orgId);
        userVo.setUserType(userType);
        userVo.setCompanyId(companyId);
        //初始登录次数为零
        userVo.setLoginTimes(Constants.NEW_REGISTERER);
        
        try {
        	int flag = Constants.SQL_RESULT_ERROR;
        	
        	List<User> userPhone = userService.selectUserIfPhoneExists(phone, userType);
            if (!StringUtils.isEmpty(id)) {
            	if(userPhone != null && userPhone.size() > 0 && !(userPhone.get(0).getId()).equals(id)){
            		result.setSuccess(false);
                    result.setMsg("用户号码已存在!");
                    return result;
            	}
            	
                userVo.setModifydatetime(DateUtils.gettimestamp());
                userVo.setId(id);
                flag = userService.updateByPrimaryKeySelective(userVo);
                result.setSuccess(true);
            } else {
            	if(userPhone != null && userPhone.size() > 0){
            		result.setSuccess(false);
                    result.setMsg("用户号码已存在!");
                    return result;
            	}
            	
                //自动生成帐户编号
                String account = userService.getNewUserNo(userType);
                userVo.setLoginname(account);
                
                if (userService.selectUserIfExists(userVo.getLoginname())) {
                    result.setSuccess(false);
                    result.setMsg("用户账号生成失败，请稍后重试!");
                    return result;
                }
                
                userVo.setId(UniqueNumberUtils.get18UniqueNumber());
                userVo.setCreatedatetime(DateUtils.gettimestamp());
                userVo.setState(USER_STATE);
                
                String password = Globals.getConfig("account_password");   
//                password = DESEncryption.encrypt(password, account);//两次加密
                userVo.setPwd(MD5Util.string2MD5(password));
                
                flag = userService.insert(userVo);
                LogUtils.insertLog("新增用户信息", userVo.getId(), request);

                result.setSuccess(true);
            }
            
           
            if(flag == Constants.SQL_RESULT_SUCCESS){
            	 //用户插入成功，插入对应的用户角色
            	userService.updateRoleUser(userVo.getId(), roles);
                result.setSuccess(true);
                
                //用户插入成功，插入对应的店铺信息
                shopInfoService.updateUserShop(userVo.getId(), shopIds);
                LogUtils.insertLog("编辑用户信息", userVo.getId(), request);
            }
            
            result.setObj(CommonService.getSessionUser().getId());
        
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    
    /**
     * 重置密码
     * 
     * @param id	用户ID
     * @param lname	登录名
     * @param pwd	密码
     * @param request
     * @return
     */
    @RequestMapping(value = "resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson resetPwd(String id, String lname ,  String pwd , HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User userVo = new User();
        
        try {
        	if (!checkIfUserAllPermission(id)) {
				result.setSuccess(false);
				result.setMsg("您没有该用户的操作权限");
				return result;
			}
        	
        	userVo.setId(id);
        	userVo.setPwd(pwd);
            userVo.setModifydatetime(DateUtils.gettimestamp());
            userService.updateByPrimaryKeySelective(userVo);
            result.setSuccess(true);
            LogUtils.insertLog("重置用户密码", userVo.getId(), request);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 修改用户密码
     * @param id 用户id
     * @return 跳转页面url
     * @author liuying 1075817474@qq.com
     * @date 2016年5月11日
     * @see 
     */
    @RequestMapping(value = "changePassword", method = RequestMethod.GET)
	public String changePassword(Model model, String id) {
		try {
			if (!String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				User userVo = userService.selectByPrimaryKey(id);
				model.addAttribute("user", userVo);
			}

		} catch (Exception e) {
		}
		return "common/changePassword";
	}
    
    /**
     * @Description 保存密码
     * @param id 主键id
     * @param uname 用户名
     * @param oldPwd 当前密码
     * @param newPwd 新密码
     * @param req 用户请求
     * @return 响应结果
     * @author liuying 1075817474@qq.com
     * @date 2016年5月12日
     * @see 
     */
    @RequestMapping(value = "savePassword", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson savePassword(String id, String lname, String oldPwd, String newPwd, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            //校验的用户对象
        	final User user = userService.selectByPrimaryKey(id);
        	
        	//更新密码的用户对象
            User userVo = new User();
            
            //生成密匙
//        	final String oldUserKey = MD5Util.generalPassword(lname, oldPwd);
//        	final String newUserKey = MD5Util.generalPassword(lname, newPwd);
        	
        	//密码校验
			if(oldPwd.equals(user.getPwd())){
	        	userVo.setId(id);
	        	userVo.setPwd(newPwd);
	            userService.updateByPrimaryKeySelective(userVo);
	            result.setSuccess(true);
	            result.setMsg("操作成功");
	            LogUtils.insertLog("保存用户密码", userVo.getId(), req);
			}else{
				result.setMsg("密码错误");
				result.setSuccess(false);
			}
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    
    @RequestMapping(value = "checkIfUserPermission", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson checkIfUserPermission(String id) {
        RequestJson result = new RequestJson();
        try {
        	User user = userService.selectByPrimaryKey(id);
        	if(user.getUserType() != Constants.OWNER_TYPE){
        		List<RoleUser> roles = userService.queryRoleByUserId(id);
        		for(RoleUser item : roles){
        			//只要有一个角色该用户有权限，那就能操作它
        			if(roleService.ifCurrAdmin() || roleService.checkIfRolePermission(item.getRoleId())){
        				result.setSuccess(true);
        	            return result;
        			}
        		}
        	}
        	
        	result.setSuccess(false);
            result.setMsg("您没有任何有关权限，无法编辑此用户");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    
    /** 
     * @Title: checkIfUserAllPermission 
     * @Description: 检查用户是否有操作此账号的所有权限
     * @param @param id 用户ID
     * @param @return     
     * @return boolean     
     * @throws 
     */
    public boolean checkIfUserAllPermission(String id) {
		User user = userService.selectByPrimaryKey(id);
		if (user.getUserType() != Constants.OWNER_TYPE) {
			List<RoleUser> roles = userService.queryRoleByUserId(id);
			for (RoleUser item : roles) {
				// 只要有一个角色该用户没权限，那就不能操作它
				if (!roleService.ifCurrAdmin() && !roleService.checkIfRolePermission(item.getRoleId())) {
					return false;
				}
			}
		}
		return true;
    }
    
    /**
     * @Description 修改用户状态
     * @param id
     *            用户id
     * @param state
     *            用户状态
     * @param req
     *            用户请求
     * @return 请求的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "updateState", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateState(String id, int state, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
			if (!checkIfUserAllPermission(id)) {
				result.setSuccess(false);
				result.setMsg("您没有该用户的操作权限");
				return result;
			}
        	
            userService.updateState(id, state);
            result.setSuccess(true);
            result.setMsg("操作成功");
            LogUtils.insertLog("新增用户信息", id, req);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }

        return result;
    }

    /**
     * @Description 批量删除用户
     * @param userIDs
     *            用户的id
     * @return 删除的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "deletePage", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deletePage(String userIDs,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
			String ids[] = userIDs.split("\\,");
			for (int i = 0; i < ids.length; i++ ) {
			    userService.deleteByPrimaryKey(ids[i]);
			}
			LogUtils.insertLog("批量删除用户", user.getId(), req);
			result.setSuccess(true);
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
    }

    /**
     * @Description 根据部门id查询该部门下的用户
     * @param orgId
     *            部门id
     * @return 查询的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "getByOrgId", method = RequestMethod.GET)
    public RequestJson getByOrgId(@QueryParam("orgId") String orgId) {
        RequestJson result = new RequestJson();
        try {
            result.setObj(userService.selectByOrgId(orgId));
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * @Description 根据主键查询用户
     * @param id 用户id
     * @param userType 账号类型
     * @return 查询的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "selectPK", method = RequestMethod.GET)
    public String selectByPrimaryKey(Model model, @QueryParam("id") String id, Integer userType, String keyword) {
        try {
        	User user = new User();
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
                
                //当进入运营的新增页面时，默认为面向平台
                if(userType == Constants.COMPANY_TYPE_PROPERTY){
                	user.setUserType(Constants.ADMIN_TYPE);
                }else{
                	user.setUserType(userType);
                }
            } else {
                user = userService.selectByPrimaryKey(id);
                model.addAttribute("type", Constants.EDIT_TYPE);
                model.addAttribute("roleId", user.getRoleId());
                
            }
            model.addAttribute("user", user);
            
            //所有相关角色
            List<Role> roles = roleService.getRoleList(user.getUserType(),keyword);
            //当前账户的角色
            List<RoleUser> uRoles = userService.queryRoleByUserId(id);
            //最终角色集合：当前账户的角色+我这个用户有权限操作的角色
            List<Role> permissionRoles = new ArrayList<Role>();
            //该用户是否有当前账户的全部权限，决定它能不能对账户进行修改其他信息操作
            boolean isAllPermissionHave = true;
            for(Role item : roles){
            	item.setDisabled(false);
            	boolean isAdded = false;
            	
            	//该用户没有权限的角色无法修改
            	if(!roleService.ifCurrAdmin() && !roleService.checkIfRolePermission(item.getId())){
            		item.setDisabled(true);
            	}else{
            		permissionRoles.add(item);
            		isAdded = true;
            	}
            	
            	for(RoleUser j : uRoles){
            		if(item.getId().equals(j.getRoleId())
            				&& !isAdded){
            			permissionRoles.add(item);
            		}
            		
                	j.setDisabled(false);
                	//该用户没有权限的角色无法修改
                	if(!roleService.ifCurrAdmin() && !roleService.checkIfRolePermission(j.getRoleId())){
                		j.setDisabled(true);
                		isAllPermissionHave = false;
                	}
                }
            }
            model.addAttribute("roles", permissionRoles);
            model.addAttribute("uRoles", uRoles);
            model.addAttribute("isAllPermissionHave", isAllPermissionHave);
            
            List<Dict> userTypes = dictService.getDictFromCache("userType");
            model.addAttribute("userTypes", userTypes);
            
            
            switch (userType) {
			case Constants.OPERATION_TYPE:
				model.addAttribute("operationCompanys", operationCompanyService.getAllCompany());
				break;
			case Constants.PROPERTY_TYPE:
				model.addAttribute("propertyCompanys", propertyCompanyService.getAllCompany());
				break;
			case Constants.DISTRIBUTION_TYPE:
				model.addAttribute("distributionCompanys", distributionCompanyService.getAllCompany());
	            break;
			case Constants.BUSINESS_TYPE:
				List<String> shops = shopInfoService.getShopIdsByUserId(id);
				if(shops != null && shops.size() > 0){
            		StringBuffer buffer = new StringBuffer();
            		for(String item : shops){
            			buffer.append(item + ",");
            		}
            		
            		String shopsStr = buffer.substring(0, buffer.length() - 1);
            		model.addAttribute("shops" , shopsStr);
				}
	            break;
			default:
				break;
			}
            
        } catch (Exception e) {
        }
        return "system/user/userEdit";
    }
    
    @RequestMapping(value = "getRUser", method = RequestMethod.GET)
    public String getRUser(Model model,@QueryParam("userId") String userId, @Context HttpServletRequest req) {
        try {

        } catch (Exception e) {
        }
        return "system/user/userRole";
    }

    
    @RequestMapping(value = "updateRUser", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson updateRUser(@RequestParam(value="roles[]") String[] roles,String userId, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            userService.updateRoleUser(userId, roles);
            result.setSuccess(true);
            LogUtils.insertLog("更新用户角色", userId, req);
        } catch (Exception e) {
            result.setMsg("操作异常");
        }
        return result;
    }
    
    @RequestMapping(value = "getRoleList", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson getRoleList(String userId, int userType,String keyword, @Context HttpServletRequest req) {
    	RequestJson result = new RequestJson();
    	try {
           //所有相关角色
             List<Role> roles = roleService.getRoleList(userType,keyword);
             //当前账户的角色
             List<RoleUser> uRoles = userService.queryRoleByUserId(userId);
             //最终角色集合：当前账户的角色+我这个用户有权限操作的角色
             List<Role> permissionRoles = new ArrayList<Role>();
             //该用户是否有当前账户的全部权限，决定它能不能对账户进行修改其他信息操作
             for(Role item : roles){
             	item.setDisabled(false);
             	boolean isAdded = false;
             	
             	//该用户没有权限的角色无法修改
             	if(!roleService.ifCurrAdmin() && !roleService.checkIfRolePermission(item.getId())){
             		item.setDisabled(true);
             	}else{
             		permissionRoles.add(item);
             		isAdded = true;
             	}
             	
             	for(RoleUser j : uRoles){
             		if(item.getId().equals(j.getRoleId())
             				&& !isAdded){
             			permissionRoles.add(item);
             		}
                 }
             }
             
             result.setObj(JSONArray.fromObject(permissionRoles).toString());
    		result.setSuccess(true);
    	} catch (Exception e) {
    		e.printStackTrace();
    		result.setMsg("操作异常");
    	}
    	return result;
    }
    
    /**
     * @Description 生成省、市、小区、店铺树<br>
     * 
     * @param req 用户请求
     * @param response 服务器响应
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月13日
     * @see 
     */
    @RequestMapping(value="treeData" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson treeData(String[] roles,HttpServletRequest req,HttpServletResponse response){
        RequestJson result = new RequestJson();
        JSONArray jsonArr=new JSONArray();
        try {
        	Set<Map<String, String>> listcell = new HashSet<Map<String,String>>();
        	if(roles.length > 0){
        		 listcell = shopInfoService.getAllCellShopInfo(roles);
        	}
            
        	if(listcell.size() > 0){
        		
        		for(Map<String, String> item : listcell){
        			JSONObject json = new JSONObject();
        			json.put("id", item.get("id"));
        			json.put("pId", item.get("pId"));
        			json.put("name", item.get("name"));
        			json.put("chkDisabled", item.get("chkDisabled"));
        			jsonArr.add(json);
        		}
        	}
            
            result.setObj(jsonArr.toString());
        }catch (Exception e) {
           e.printStackTrace();
           result.setMsg("操作异常");
           result.setSuccess(false);
        }
        return result;
    }

    @RequestMapping(value = "queryUserShop", method = RequestMethod.GET)
    public String queryUserShop(Model model, String userId,String shops, @Context HttpServletRequest req) {
        // 新增选择店铺，弹出界面时不清除之前选择的店铺信息
        //    	if(userId != null && !"0".equals(userId) ){
            
            //取到当前与角色关联的所有小区
    		if(org.springframework.util.StringUtils.isEmpty(shops)){
    			List<String> list = shopInfoService.getShopIdsByUserId(userId);
    			model.addAttribute("shopList", list);
    		}else{
    			model.addAttribute("shopList", "[" + shops + "]");
    		}
//    	}

        return "system/user/userShop";
    }
	
	/** 
     * @Title: userdetail 
     * @Description: 用户详情
     * @param @param model
     * @param @param id
     * @param @param req
     * @param @return     
     * @return String     
     * @throws 
     */
    @RequestMapping(value = "/userdetail", method = RequestMethod.GET)
    public String userdetail(Model model, String id, HttpServletRequest req){
        try {
        	User user = userService.selectByPrimaryKey(id);
            if(user != null){
            	switch (user.getUserType()) {
    			case Constants.ADMIN_TYPE:
    				user.setCompanyName(Constants.DLIFE);
    				break;
    			case Constants.OPERATION_TYPE:
    				if(!org.springframework.util.StringUtils.isEmpty(user.getCompanyId())){
    					user.setCompanyName(operationCompanyService.selectByPrimaryKey(user.getCompanyId()).getCompanyName());
    				}
    				break;
    			case Constants.PROPERTY_TYPE:
    				if(!org.springframework.util.StringUtils.isEmpty(user.getCompanyId())){
    					user.setCompanyName(propertyCompanyService.selectByPrimaryKey(user.getCompanyId()).getCompanyName());
    				}
    				break;
    			case Constants.BUSINESS_TYPE:
    				user.setCompanyName(Constants.NO_STR);
    				break;
    			case Constants.DISTRIBUTION_TYPE:
    				if(!org.springframework.util.StringUtils.isEmpty(user.getCompanyId())){
    					user.setCompanyName(distributionCompanyService.selectByPrimaryKey(user.getCompanyId()).getCompanyName());
    				}
    				break;
    			default:
    				break;
    			}
            	
            	//业主没有角色
				if (user.getUserType() != Constants.OWNER_TYPE) {
					// 取到用户对应的角色
					List<RoleUser> roleList = userService
							.queryRoleByUserId(user.getId());
					StringBuffer buffer = new StringBuffer();
					for (RoleUser item : roleList) {
						buffer.append(item.getRoleName() + ",");
					}
					if (buffer.length() > 0) {
						user.setRoles(buffer.substring(0, buffer.length() - 1)
								.toString());
					}
				}
    			
                model.addAttribute("user", user);
            }
            
            model.addAttribute("userTypes", dictService.getDictFromCache("userType"));
        } catch (Exception e) {
        }
        
        return "system/user/userDetail";
    }
}
